package com.example.system.class02;

import java.util.Arrays;

/**
 * @Date 2022/7/17
 * @Created by Jonathan
 */
public class Code01_SelectionSort {
    public static void main(String[] args) {
        int[] arr = new int[]{3, 1, 2, 4};
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
    }


    // 0 ~ N-1 找到最小的放到0位置
    // 1 ~ N-1 找到最小的放在1位置
    private static void selectionSort(int[] arr) {
        if (arr == null || arr.length < 2) return;
        for (int i = 0; i < arr.length - 1; i++) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; j++) {
                minIndex = arr[j] < arr[minIndex] ? j : minIndex;
            }
            if (minIndex != i) {
                swap(arr, i, minIndex);
            }
        }
    }

    //
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
